<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="common.jsp"%>
<html>
<head>
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>设备信息</title>
<script type="text/javascript">
$(function() {
	$(".form_datetime").datetimepicker({
		/* 显示格式 */       
		format: "yyyy-mm-dd",
	    /* 完成关闭 */
	    autoclose: true,
	   /*  今天 时间按钮*/
	    todayBtn: true, 
	   /*  今天的时间变黄色 */
	    todayHighlight:true, 
	    /* 定位 */
	    pickerPosition: "bottom-left",
	    /* 最小值 */
	    minuteStep: 10,
	    /*  语言 */
	    language: 'zh-CN',  
		/* 分上午下午 */
	    showMeridian: true,
	    /* 分的所有 */
	    minuteStep:true,
	    startView: 2,//月视图
		minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
	}).on('hide',function(e) {  
		e.stopPropagation(); //e.stopPropagation()阻止事件冒泡
		$('#updateForm').data('bootstrapValidator').updateStatus('purchasedate', 'NOT_VALIDATED',
				null).validateField('purchasedate'); 
		$('#updateForm').data('bootstrapValidator').updateStatus('installationdate', 'NOT_VALIDATED',
				null).validateField('installationdate'); 
	});
});
</script>
<script type="text/javascript">
	$(function() {
		//1.初始化Table
		var oTable = new TableInit();
		oTable.Init();

		//2.初始化Button的点击事件
		var oButtonInit = new ButtonInit();
		oButtonInit.Init();
		//动态加载车间
		getWorkShop();
		//jQuery，既阻止默认行为又停止冒泡
	    $("#ss").on('click',function(){
	    	    return false;//当然 也阻止了事件本身
	    });
	  	//添加修改数据+检验
		$(function() {
			$("#updateForm").bootstrapValidator({
					feedbackIcons : {
						valid : 'glyphicon glyphicon-ok',
						invalid : 'glyphicon glyphicon-remove',
						validating : 'glyphicon glyphicon-refresh'
					},
					fields : {
						name : {
							validators : {
								notEmpty : {
									message : '设备名称不能为空'
								},
							}
						},
						/* tonnage : {
							validators : {
								notEmpty : {
									message : '吨位不能为空'
								},
								regexp : {
									regexp : /^[0-9]+([.]{1}[0-9]+){0,1}$/,
									message : '吨位只能是整数或小数'
								}
							}
						},
						version : {
							validators : {
								notEmpty : {
									message : '型号不能为空'
								},
							}
						},
						purchasedate : {
							validators : {
								notEmpty : {
									message : '购置日期不能为空'
								},

							}
						},
						installationdate : {
							validators : {
								notEmpty : {
									message : '安装日期不能为空'
								},

							}
						},
						factory : {
							validators : {
								notEmpty : {
									message : '设备生产厂家不能为空'
								},
							}
						}, */
						workshop : {
							validators : {
								notEmpty : {
									message : '车间不能为空'
								},
							}
						},
					},
				}).on('success.form.bv',function(e) {
					 $("#sv").on('click',function(){
				    	    return false;//当然 也阻止了事件本身
				    });
					e.preventDefault();
					var url1 = "";
					var title = "新增";
					if("新增设备信息" == $("#bt").html()){
						url1 = '${pageContext.request.contextPath}/equipment/addEqui.do';
					}else if("修改设备信息" == $("#bt").html()){
						url1 = '${pageContext.request.contextPath }/equipment/update.do';
						title = "修改";
					}
					var formData = new FormData($("#updateForm")[0]);
					$.ajax({
						type : 'post',
						url : url1,
						data : formData,
						async: false,  
				        cache: false,  
				        contentType: false,  
				        processData: false,
						success : function(data) {
							if (data == 1) {
								toastr.success(title+'成功');
								setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
									window.location.reload(); 
									resets();
								},1000);
							} else if (data == 2) {
								toastr.warning('该信息已存在，不能重复添加');
								setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
									window.location.reload(); 
								},1000);
							}else {
								toastr.error(title+'失败');
								setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
									window.location.reload(); 
								},2000);
							}
						}
					});
				});
		});
	});
	var TableInit = function() {
		var queryUrl = '${pageContext.request.contextPath }/equipment/select.do';
		var oTableInit = new Object();
		//初始化Table
		oTableInit.Init = function() {
			$('#tb_departments').bootstrapTable({
				url : queryUrl, //请求后台的URL（*）
				method : 'get', //请求方式（*）
				toolbar : '#toolbar', //工具按钮用哪个容器
				striped : true, //是否显示行间隔色
				cache : true, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
				pagination : true, //是否显示分页（*）
				sortable : false, //是否启用排序
				sortOrder : "asc", //排序方式
				exportDataType : "selected",
				queryParams : oTableInit.queryParams,//传递参数（*）
				sidePagination : "server", //分页方式：client客户端分页，server服务端分页（*）
				pageNumber : 1, //初始化加载第一页，默认第一页
				pageSize : 10, //每页的记录行数（*）
				pageList : [ 10,20,30 ], //可供选择的每页的行数（*）
				minimumCountColumns : 2, //最少允许的列数
				clickToSelect : true, //是否启用点击选中行
				height : 523,//865满屏  //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
				uniqueId : "ID", //每一行的唯一标识，一般为主键列
				cardView : false, //是否显示详细视图
				detailView : false, //是否显示父子表
				columns :[ {
					checkbox : true
				}, {
					field : 'eid'
				}, {
					field : 'name',
					title : '设备名称'
				}, {
					field : 'tonnage',
					title : '吨位'
				}, {
					field : 'version',
					title : '型号'
				}, {
					field : 'purchasedate',
					title : '购置日期'
				}, {
					field : 'installationdate',
					title : '安装日期'
				}, {
					field : 'abandonedtime',
					title : '废弃日期'
				}, {
					field : 'factory',
					title : '生产厂家'
				}, {
					field : 'workshop',
					title : '车间'
				}, {
					field : 'eqenter',
					title : '录入人'
				}, {
					field : 'eqentertime',
					title : '录入时间'
				}, {
					field : 'remark2',
					title : '状态',
					formatter:function(value,row,index){
						if(row.remark2 == "1"){
							return "闲置";
						}else if(row.remark2 == "2"){
							return "使用中";
						}else if(row.remark2 == "3"){
							return "废弃";
						}else{
							return "bug";
						}
					}
				} ],
			});
			$('#tb_departments').bootstrapTable('hideColumn', 'eid');
		};

		//得到查询的参数
		oTableInit.queryParams = function(params) {
			var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
				limit : params.limit, //页面大小
				offset : params.offset, //页码
				name : $("#name1").val(),
				factory : $("#factory1").val(),
				eqenter : $("#eqenter1").val(),
				workshop : $("#workshop1").val()
			};
			return temp;
		};
		return oTableInit;
	};
	var ButtonInit = function() {
		var oInit = new Object();
		var postdata = {};

		oInit.Init = function() {
			//初始化页面上面的按钮事件
		};
		return oInit;
	};
	//条件查询
	function selectByOther() {
		$("#tb_departments").bootstrapTable('refresh');
	}
	//删除
	function doDel() {
		//必须选中一条数据
		var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
		if (checkedItems.length <= 0) {
			toastr.warning('请选择一条数据');
		} else {
			var eids = "";
			for(var i = 0;i < checkedItems.length; i++){
				if(i != checkedItems.length-1){
					eids += checkedItems[i].eid + ",";
				}else{
					eids += checkedItems[i].eid;
				}
			}
			//询问框
			Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
				function(e) {
					if (!e) {return;}
					$.ajax({
						type : 'POST',
						url : '${pageContext.request.contextPath }/equipment/equiDel.do',
						data:'eids=' + eids,
						success : function(data) {
							if (data > 0) {
								$("#tb_departments").bootstrapTable('refresh');
								toastr.success('删除成功');
							} else {
								toastr.error('Error');
							}
						}
					});
				});
		}
	}
	//打开添加模态框
	function doAdd() {
		$("#updateForm")[0].reset();
		$("#bt").html("新增设备信息");
		$("#updateModal").modal(open);
	}
	//关闭添加form表单时清空数据
	function resets() {
		$('#updateForm').data('bootstrapValidator').resetForm(true);
		$('#workshop').selectpicker('val',"");
	} 
	//导出所有
	function exportAll() {
		Ewin.confirm({message : "确认要导出所有的数据吗？"}).on(
			function(e) {
				if (!e) {return;}
					window.location.href = "${pageContext.request.contextPath }/equipment/exportAll.do";
			});
	};
	//动态获取车间
	function getWorkShop() {
		$.ajax({
			type : "post",
			url : "${pageContext.request.contextPath }/quality/selworkshop.do",
			success : function(data) {
				var str = "<option value='' selected='selected'>--请选择--</option>";
				var json = eval('(' + data + ')');
				for (var i = 0; i < json.data.length; i++) {
					var id = json.data[i].id;
					var name = json.data[i].name;
					str += '<option value="'+id+'">' + name + '</option>';
				}
				$("#workshop").append(str);
				$("#workshop1").append(str);
				$("#workshop").selectpicker('refresh');
				$("#workshop1").selectpicker('refresh');
			}
		});
	}
	//修改，id查询并赋值给修改模态框
	function doUpdate() {
		//必须选中一条数据
		var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
		if (checkedItems.length == 1) {
			$("#bt").html("修改设备信息");
			$("#updateModal").modal("show");
			$.ajax({
				type:"post",
				url: '${pageContext.request.contextPath }/equipment/equiSelByID.do?eid='+checkedItems[0].eid,
				success:function(data){
					var json = eval('('+data+')');
					$("#eid").val(json.rows[0].eid);
					$("#name").val(json.rows[0].name);
					$("#tonnage").val(json.rows[0].tonnage);
					$("#version").val(json.rows[0].version);
					$("#purchasedate").val(json.rows[0].purchasedate);
					$("#installationdate").val(json.rows[0].installationdate);
					$("#abandonedtime").val(json.rows[0].abandonedtime);
					$("#factory").val(json.rows[0].factory);
					$("#eqenter").val(json.rows[0].eqenter);
					$("#eqentertime").val(json.rows[0].eqentertime);
					$("#remark2").val(json.rows[0].remark2);
					$('#workshop').selectpicker('val',json.rows[0].workshop);
				}
			});
		} else {
			toastr.warning('请只选择一条数据');
		}
	}
	function douploadModal() {
		$('#uploadModal').modal(open);
		//清空表单
		document.getElementById("importForm").reset();
	}
	function uploadBtn() {
		 var fileName = $("#fileInput").val();
		 if (fileName.length > 0) {
		     var formData = new FormData($("#importForm")[0]);  
		     $.ajax({  
		          url: '${pageContext.request.contextPath}/equipment/uplodeFile.do' ,  
		          type: 'post',  
		          data: formData,
		          async: false,  
		          cache: false,
		          contentType: false,  
		          processData: false,
		          success: function (data) { 
		        	  if (data == 1) {
		        		  toastr.success("文件导入成功（重复数据已过虑）！");
		        		  setTimeout(function() {//使用setTimeout()方法设定定时2000毫秒
							window.location.reload(); 
						  },1000);
		        	  }else{
		        		  toastr.warning('文件格式异常，文件导入失败！'); 
		        		  setTimeout(function() {//使用setTimeout()方法设定定时2000毫秒
								window.location.reload(); 
							  },1000);
		        	  }
		          },
		          error: function (data) {
		        	  toastr.error("文件格式异常，文件导入失败！");  
		        	  setTimeout(function() {//使用setTimeout()方法设定定时2000毫秒
							window.location.reload(); 
						  },1000);
		          } 
		     }); 
		 }else{
			 toastr.warning('上传文件为空，请选择要导入的文件！'); 
			 setTimeout(function() {//使用setTimeout()方法设定定时2000毫秒
					window.location.reload(); 
				  },1000);
		}
	}
	//导出数据模板
	function doExportFile() {
		Ewin.confirm({message : "确认要导出数据模板吗？"}).on(
			function(e) {
				if (!e) {return;}
			window.location.href = "${pageContext.request.contextPath}/equipment/doExportFile.do"; 
			$('#uploadModal').modal('hide'); 
		});
	}
	toastr.options.positionClass = 'toast-top-center';
</script>
</head>
<body>
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content">
      			<div class="modal-header">
        			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
        				<span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span style="font-size:13px">excel导入</span>
        			</h4>
      			</div>
      			<div class="modal-body">
	        		<form id="importForm" class="form-horizontal">
	        			<div class="form-group">
							<label  class="col-sm-3 control-label"></label>
							<div class="col-sm-7"> 
		           				 <button id="btn_delete" type="button" class="btn btn-default" 
		           				 	onclick="doExportFile()">
					                <span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出数据模板
					            </button>
	          				 </div>
	          			</div>
	          			<div class="form-group">
				            <label class="col-sm-5 control-label">excel文件:</label>
				            <div class="col-sm-5"> 
					            <input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
	          				</div>
	          			</div>
	        			<div class="form-group"> 
				   			<div class="col-sm-3 col-sm-offset-7">  
						        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						        <button type="submit"  name="submit"  class="btn btn-primary" id="ss" 
						        	onclick="uploadBtn()">导入</button>
			      			</div>
			      		</div>
	        		</form>
	      		</div>
    		</div>
  		</div>
	</div>
	<div class="panel-body" style="padding-bottom: 0px;">
		<div class="panel panel-default">
			<div class="panel-heading">查询条件</div>
			<div class="panel-body">
				<form id="formSearch" class="form-horizontal">
					<div class="form-group" style="margin-top: 15px">
						<label class="control-label col-sm-1" for="name1">设备名称</label>
						<div class="col-sm-3">
							<input type="text" class="form-control" id="name1">
						</div>
						<label class="control-label col-sm-1" for="factory1">生产厂家</label>
						<div class="col-sm-3">
							<input type="text" class="form-control" id="factory1">
						</div>
						<br> <br> <br> 
						<label class="control-label col-sm-1" for="eqenter1">录入人</label>
						<div class="col-sm-3">
							<input type="text" class="form-control" id="eqenter1">
						</div>
						<label class="control-label col-sm-1" for="workshop1">车间</label>
						<div class="col-sm-3">
							<select class="selectpicker show-tick form-control" data-live-search="true" id="workshop1">
							</select>
						</div>
						<div class="col-sm-4" style="margin-top: -30px;">
							<button type="button" style="margin-left: 20%;"
								id="btn_query" class="btn btn-primary" onclick="selectByOther()"
								data-query-params="queryParams" data-query-params-type="limit">查询</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>

	<div id="toolbar" class="btn-group">

		<button id="btn_add" type="button" class="btn btn-default" onclick="doAdd()">
			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
		</button>
		<button id="btn_edit" type="button" class="btn btn-default" onclick="doUpdate()">
			<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
		</button>
		<button id="btn_delete" onclick="doDel()" type="button" class="btn btn-default">
			<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
		</button>
		<button id="btn_import" type="button" class="btn btn-default" onclick="douploadModal()">
                <span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>导入
            </button>
		<button id="btn_export" type="button" class="btn btn-default" onclick="exportAll()">
			<span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出所有
		</button>
		<button id="btn_hide" type="button" class="btn btn-default" style="display: none;">
			<span class="glyphicon glyphicon-cancel" aria-hidden="true"></span>隐藏
		</button>
	</div>
	<table id="tb_departments"></table>
	<!-- 添加修改弹出框 -->
	<div class="modal fade" id="updateModal" tabindex="-1" role="dialog"
		aria-labelledby="updateModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close" aria-hidden="true" onclick="resets()">&times;</button>
					<h4 class="modal-title" id="updateModalLabel">
						<span id="bt" style="font-size:13px"></span>
					</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="updateForm" method="post">
					<input type="hidden" id="eid" name="eid">
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">设备名称:</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input type="text" class="form-control" id="name" name="name" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="tonnage" class="col-sm-3 control-label">吨位:</label>
							<div class="col-sm-9">
								<input type="text" class="form-control" name="tonnage" id="tonnage" 
								style="width: 85%;">
							</div>
						</div>
						<div class="form-group">
							<label for="version" class="col-sm-3 control-label">型号:</label>
							<div class="col-sm-9">
								<input type="text" class="form-control" name="version"
									id="version" style="width: 85%;">
							</div>
						</div>
						<div class="form-group">
							<label for="purchasedate" class="col-sm-3 control-label">购置日期:</label>
							<div class="col-sm-9">
								<input type="text" name="purchasedate" id="purchasedate" 
									placeholder="yyyy-MM-dd" style="width: 85%;" 
										class="form_datetime form-control" readonly="readonly">
							</div>
						</div>
						<div class="form-group">
							<label for="installationdate" class="col-sm-3 control-label">安装日期:</label>
							<div class="col-sm-9">
								<input type="text" name="installationdate" id="installationdate" 
									placeholder="yyyy-MM-dd" style="width: 85%;" 
										class="form_datetime form-control" readonly="readonly">
							</div>
						</div>
						<div class="form-group">
							<label for="factory" class="col-sm-3 control-label">生产厂家:</label>
							<div class="col-sm-9">
								<input type="text" class="form-control" id="factory" name="factory" style="width: 85%;">
							</div>
						</div>
						<div class="form-group">
							<label for="workshop" class="col-sm-3 control-label">车间:</label>
							<div class="col-sm-8" style="width: 385px;">
								<select class="selectpicker show-tick form-control" id="workshop" name="workshop">
								</select>
								<span class="xing"></span>
							</div>
						</div>
						<input type="hidden" name="eqenter" id="eqenter">
						<input type="hidden" name="eqentertime" id="eqentertime">
						<input type="hidden" name="remark2" id="remark2">
						<div class="form-group">
							<label for="abandonedtime" class="col-sm-3 control-label">废弃日期:</label>
							<div class="col-sm-9">
								<input type="text" name="abandonedtime" id="abandonedtime" 
									placeholder="yyyy-MM-dd" style="width: 85%;"
								class="form_datetime form-control" readonly="readonly">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal" 
								onclick="resets()">关闭</button>
							<button type="submit" class="btn btn-primary" id="sv">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>